package com.eenie.common.subscribes;

import android.content.Context;
import android.content.DialogInterface;


import com.blankj.utilcode.util.ToastUtils;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import io.reactivex.observers.DefaultObserver;


public abstract class ProgressSubscriber<T> extends DefaultObserver<T> implements DialogInterface.OnDismissListener {

    private static final String TAG = "ProgressSubscriber";
    private Context context;

    QMUITipDialog mTipDialog;

    public ProgressSubscriber(Context context) {
        this.context = context;
        mTipDialog = new QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("加载中...")
                .create(true);

        mTipDialog.setOnDismissListener(this);
    }

    public ProgressSubscriber(Context context, CharSequence msg) {
        this.context = context;
        mTipDialog = new QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord(msg)
                .create(true);
        mTipDialog.setOnDismissListener(this);
    }

    public ProgressSubscriber() {

    }


    private void showProgressDialog() {
        if (mTipDialog != null) {
            mTipDialog.show();
        }

    }

    private void dismissProgressDialog() {
        if (mTipDialog != null) {
            mTipDialog.dismiss();
        } else {
            onFinish();
        }
    }


    @Override
    public void onStart() {
        showProgressDialog();
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();

    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        dismissProgressDialog();
        handleError(e);
        onFinish();
    }

    @Override
    public abstract void onNext(T t);

    public abstract void onFinish();


    public void handleError(Throwable e) {
        ToastUtils.showShort(e.getMessage());
    }


    @Override
    public void onDismiss(DialogInterface dialogInterface) {
        dialogInterface.dismiss();
        cancel();
        onFinish();
    }
}
